package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预约设置
 */
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Autowired
    ServletContext servletContext;

    @Reference
    private OrderSettingService orderSettingService;


    /**
     * Excel文件上传，并解析文件内容保存到数据库
     *
     * @param excelFile
     * @return
     */
    @RequestMapping("upload")
    public Result upload(@RequestParam("excelFile")MultipartFile excelFile){
        try {
            List<String[]> list = POIUtils.readExcel(excelFile);
            //将list转换成 List<OrderSetting>格式
            List<OrderSetting> data = new ArrayList<>();
            for (String[] strings : list) {
                String orderDate = strings[0];
                String number = strings[1];
                OrderSetting orderSetting = new OrderSetting(new Date(orderDate),Integer.parseInt(number));
                data.add(orderSetting);
            }
            System.out.println("data size:"+data.size());
            orderSettingService.add(data);
        } catch (IOException e) {
            e.printStackTrace();
            //文件解析失败
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true,MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }
    /**
     * 根据日期查询预约设置数据(获取指定日期所在月份的预约设置数据)
     *
     * @param date
     * @return
     */
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date) {//参数格式为：2019‐03-01  2019‐03-31
        try {
            List<Map> list = orderSettingService.getOrderSettingByMonth(date);
            //获取预约设置数据成功
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            //获取预约设置数据失败
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }
    /**
     * 根据指定日期修改可预约人数
     *
     * @param orderSetting
     * @return
     */
    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) { //{a: "2019-08-11", b: "1111"}
        try {
            orderSettingService.editNumberByDate(orderSetting);
            //预约设置成功
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //预约设置失败
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }


    /**
     * 下载模版
     *
     * @return
     */
    @RequestMapping("/downTemplate")
    public void downTemplate(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("text/html;charset=utf-8");
        String name = "ordersetting_template.xlsx";
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            //获取下载文件所在路径
            System.out.println(request.getServletPath());
            System.out.println(servletContext.getRealPath("/"));

            String path = servletContext.getRealPath("/template/"+name);
            System.out.println(path);

            //文件
            File file = new File(path);
            //判断文件是否存在
            if (file.exists()){
                //且仅当此对象抽象路径名表示的文件或目录存在时，返回true
                response.setContentType("application/octet-stream");
                //控制下载文件的名字
                response.setHeader("content-Disposition","attachment;filename=ordersetting_template.elsx");//指定以附件的形式进行下载
                byte buf[] = new byte[1024];

                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                os = response.getOutputStream();
                int i = bis.read(buf);
                while (i != -1){
                    os.write(buf,0,i);
                    i = bis.read(buf);
                }
            }else {
                System.out.println("您下载的资源已经不存在了");
            }
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                os.close();
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
